package com.library.management.service.book.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.library.management.domain.book.Book;
import com.library.management.domain.borrow.Borrow;
import com.library.management.mapper.book.BookMapper;
import com.library.management.service.book.BookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    
    @Override
    public boolean addBook(Book book) {
        // 设置初始可借册数等于总册数
        if (book.getTotalCopies() != null) {
            book.setAvailableCopies(book.getTotalCopies());
        }
        return this.save(book);
    }



    @Override
    public boolean updateBook(Book book) {
        // 更新时保持可借册数不变，除非总册数减少
        Book oldBook = this.getById(book.getId());
        if (oldBook != null && book.getTotalCopies() != null && 
            book.getTotalCopies() < oldBook.getTotalCopies()) {
            int borrowed = oldBook.getTotalCopies() - oldBook.getAvailableCopies();
            book.setAvailableCopies(Math.max(0, book.getTotalCopies() - borrowed));
        }
        return this.updateById(book);
    }
    
    @Override
    public boolean deleteBook(Long id) {
        return this.removeById(id);
    }
    
    @Override
    public boolean updateBookStatus(Long id, Integer status) {
        Book book = new Book();
        book.setId(id);
        book.setStatus(status);
        return this.updateById(book);
    }
    
    @Override
    public boolean batchAddBooks(List<Book> books) {
        return this.saveBatch(books);
    }
} 